﻿using DataWorks_IBLL;
using DataWorks_Sqlite.MappingClass;
using DataWorks_Tools.ProcessExcute.Merge;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection;

namespace DataWorks_WebApi.Controllers
{
    [EnableCors("react")]
    [Route("[controller]/[action]")]
    [ApiController]
    public class DW_PropsHalfHourCombineController : ControllerBase
    {
        private readonly ILogger<DW_PropsHalfHourCombineController> _logger;
        private readonly IBLL_Props_HalfHourCombine  _bLL_Props_HalfHourCombine;
        private readonly IBLL_Props_Admin _bLL_Props_Admin;
        private readonly string controllerName;
        private readonly IMemoryCache _memoryCache;//内存缓存
        public DW_PropsHalfHourCombineController(ILogger<DW_PropsHalfHourCombineController> logger, IBLL_Props_HalfHourCombine  bLL_Props_HalfHourCombine, IBLL_Props_Admin bLL_Props_Admin, IMemoryCache memoryCache)
        {
            _logger = logger;
            _bLL_Props_HalfHourCombine = bLL_Props_HalfHourCombine;
            //_memoryCache = memoryCache;
            controllerName = this.GetType().Name;
            _bLL_Props_Admin = bLL_Props_Admin;
            _memoryCache = memoryCache;
        }

        [HttpGet]
        public IActionResult GetPropsHalfHourCombine(int page, int pagesize, string loginname)
        {
            var data = _bLL_Props_HalfHourCombine.LoadEntities(a => a.loginname==loginname);
            var datacount=data.Count();
            var pagedata= data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok( new { pagedata, total = datacount });
        }

        [HttpPost]
        public IActionResult AddPropsHalfHourCombine([FromBody] dw_props_halfhourcombine row)
        {
            //先按照key来排序获得最后一个数据
            var last = _bLL_Props_HalfHourCombine.LoadEntities(a => true).OrderBy(a => a.key).LastOrDefault();
            if (last != null)
            {
                //把要添加的数据的key改为最后一个数据的key+1，这样数据库里就是连续的数据，不会出现断档的key
                row.key = last.key + 1;
            }
            else
            {
                row.key = 1;
            }
            var isaddsucess = _bLL_Props_HalfHourCombine.AddEntity(row);
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            if (isaddsucess)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                return Ok("添加成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("添加失败");
            }
        }

        [HttpPut]
        public IActionResult EditPropsHalfHourCombine([FromBody] dw_props_halfhourcombine row)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var iseditsucess= _bLL_Props_HalfHourCombine.EditEntity(row);
            
            if (iseditsucess)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                return Ok("编辑成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("编辑失败");
            }
        }
        [HttpDelete]
        public IActionResult DelPropsHalfHourCombine(int key)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var data = _bLL_Props_HalfHourCombine.LoadEntities(a => true).Where(a=>a.key==key).FirstOrDefault();

            if (data != null)
            {
                var isdelsuccess= _bLL_Props_HalfHourCombine.DeleteEntity(data);
                if (isdelsuccess)
                {
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行成功：{DateTime.Now}");
                    return Ok("删除成功");
                }
                else
                {
                    _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败：{DateTime.Now}");
                    return BadRequest("删除失败");

                }
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败-找不到数据：{DateTime.Now}");
                return BadRequest("无法删除");
            }

        }

        /// <summary>
        /// 执行数据spikeremove流程
        /// </summary>
        /// <param name="loginname">用户名</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExcuteDataHalfHourCombine(dw_props_halfhourcombine row)
        {

            try
            {
                var adminprops = _memoryCache.GetOrCreate<dw_props_admin>("adminprops", value =>
                {
                    value.SlidingExpiration = TimeSpan.FromMinutes(10);
                    return _bLL_Props_Admin.LoadEntities(a => true).First();
                });
                var t=await HalfHourMergeProcess.HalfHourMergeProcessExcute(adminprops,row);
                string result = string.Join(Environment.NewLine, t);
                _logger.LogWarning(result);
                return Ok(result);
            }
            catch (Exception ex)
            {
                var t = MethodBase.GetCurrentMethod();
                string? methodName = t?.Name;
                _logger.LogError($"{controllerName}控制器{methodName}方法,用户名为{row.loginname}执行失败，失败原因为{ex.Message}：{DateTime.Now}");
                throw;
            }

        }
       
    }
}
